import AMapLoader from '@amap/amap-jsapi-loader'
import '@amap/amap-jsapi-types'
import { useFullscreen } from 'ahooks'
import { debounce } from 'lodash-es'
import { useContext, useEffect, useRef, useState } from 'react'

import ViewLoading from '@/components/ViewLoading'
import { UIHEIGHT, UIWIDTH } from '@/constant/common'
import { provinceCityDistrictObj } from '@/constant/provinceCityDistrictObj'
import { LoginEnt } from '@/models/LoginEnt'
import { useAppSelector } from '@/redux/store'
import { loginEntSlice } from '@/redux/toolkitSlice/loginEntSlice'
import { useDispatch } from 'react-redux'
import WrapperHeader from '../BigScreenBase/Compoments/WrapperHeader'
import type {
  AssociationData,
  SwitchAndIntervalRef
} from '../BigScreenBase/interface'
import Center from './Center'
import Left, { LeftRef } from './Left'
import Right from './Right'

import { useNavigate } from 'react-router-dom'
import '../BigScreenBase/module.less'
import BigScreenContext from '../Context/BigScreenContext'
import './index.less'

function BigScreenGovern() {
  const dispatch = useDispatch()
  const { onSlideToRight, onSlideToLeft } = useContext(BigScreenContext)
  const navigator = useNavigate()
  const {
    entId: initialEntId,
    entTypeCode,
    entName,
    regionCode,
    operateEntFlag,
    selectedEnt
  } = useAppSelector((state) => {
    // console.log('--state.loginEnt--:', state.loginEnt);
    return state.loginEnt
  })

  const entId =
    selectedEnt && selectedEnt.entId ? selectedEnt.entId : initialEntId
  // console.log('---3屏--entId--:', entId);

  const [viewLoading, setViewloading] = useState<boolean>(false)

  const largeScreenContainer = useRef<HTMLDivElement>(null)
  const containerWrapperRef = useRef<HTMLDivElement>(null)
  const [weatherPlugin, setWeatherPlugin] = useState<any>()

  const LeftCompRef = useRef<LeftRef>(null)
  const CenterCompRef = useRef<SwitchAndIntervalRef>(null)
  const RightCompRef = useRef<SwitchAndIntervalRef>(null)

  // 标题协会切换
  const [selectedAssociationItem, setSelectedAssociationItem] =
    useState<AssociationData>({
      key: entId,
      label: '',
      regionCode,
      operateEntFlag,
      regionCodeValue: ''
    })
  const selectedAssociationKeyRef = useRef<string>(entId)

  //全屏显示
  const [isFullscreen, { toggleFullscreen }] =
    useFullscreen(largeScreenContainer)
  const isFullscreenRef = useRef<boolean>(isFullscreen)

  //地图
  const AMapRef = useRef<any>()

  //设置地图中心
  function _setMapCenter(regionCode: string | undefined) {
    if (regionCode) {
      const centerStr = (provinceCityDistrictObj[regionCode] ?? {}).center
      if (centerStr) {
        const center = centerStr.split(',')
        const centerLnglat = new AMap.LngLat(
          Number(center[0]),
          Number(center[1])
        )
        AMapRef.current.setCenter(centerLnglat)
      }
    }
  }

  function _resizeCanvas() {
    // console.log("--resize图表--")
    // LeftCompRef.current?.resize?.()
  }

  //大屏 等比缩放
  function _setWrapperSize(largeScreenDom: HTMLDivElement) {
    const { clientWidth, clientHeight } = largeScreenDom ?? {}
    if (!clientWidth || !clientHeight) {
      //切换页签时，clientWidth === 0，clientHeight===0
      setTimeout(() => {
        // console.log("--1s执行--clientWidth--clientHeight--：", clientWidth, clientHeight)
        _setWrapperSize(largeScreenDom)
      }, 1000)
      return
    }

    let widthScale, heightScale

    if (isFullscreenRef.current) {
      widthScale = window.innerWidth / UIWIDTH
      heightScale = window.innerWidth / UIHEIGHT
    } else if (clientWidth && clientHeight) {
      widthScale = clientWidth / UIWIDTH
      heightScale = clientHeight / UIHEIGHT
    }

    const finalScale =
      widthScale && heightScale ? Math.min(widthScale, heightScale) : 1 //取小者，保持等比缩放，dom尺寸/内容不变形
    containerWrapperRef.current!.style.transform = `scale(${finalScale}) translate(-50%, -50%)`
  }

  //全屏操作 也会触发window.resize()
  const debounceResize = debounce(() => {
    // console.log("--debounceResize--isFullscreen--:", isFullscreen)
    _setWrapperSize(largeScreenContainer.current!)
    _resizeCanvas()
  }, 500)

  useEffect(() => {
    isFullscreenRef.current = isFullscreen
    window.addEventListener('resize', debounceResize) //初始化的时候不执行
    return () => {
      window.removeEventListener('resize', debounceResize)
    }
  }, [isFullscreen])

  //协会切换
  const handleAssociationClick = (associationItem: AssociationData) => {
    const key = associationItem.key
    // console.log("--handleAssociationClick--associationItem--:", associationItem)
    if (selectedAssociationKeyRef.current === key) return
    dispatch(
      loginEntSlice.actions.updateSelectedEnt(
        new LoginEnt({
          ...associationItem,
          entId: key,
          entName: associationItem.label
        })
      )
    )
    setSelectedAssociationItem(associationItem)
    selectedAssociationKeyRef.current = key
    CenterCompRef.current?.switchAssociation(key)
    RightCompRef.current?.switchAssociation(key)
  }

  useEffect(() => {
    if (!largeScreenContainer.current || !containerWrapperRef.current) return
    _setWrapperSize(largeScreenContainer.current)
    AMapLoader.load({
      key: import.meta.env.VITE_AMAP_APPKEY,
      version: '2.0',
      plugins: ['AMap.Weather']
    }).then((AMap) => {
      setViewloading(false)
      setWeatherPlugin(new AMap.Weather()) // 天气
      const mapOptions: AMap.MapOptions = {
        zoom: 10, //, //[3,20]
        zooms: [5, 20], //中国地图，
        viewMode: '2D', //设置地图模式
        mapStyle: 'amap://styles/grey', //dark
        features: ['bg', 'point', 'road'], // 设置地图显示要素 ['bg', 'road', 'building', 'point']
        defaultCursor: 'default'
      }
      const map = new AMap.Map('governMapContainer', mapOptions)

      AMapRef.current = map
      _setMapCenter(regionCode)

      //为了弥补grey主题色的颜色不符合产品要求
      map.on('complete', () => {
        //启用地图范围限制
        const bounds = new AMap.Bounds(
          new AMap.LngLat(52.982575, 3.449744),
          new AMap.LngLat(160.358813, 57.048735)
        ) //西南角,东北角
        map.setLimitBounds(bounds) //getBounds：获取当前地图可视区域范围
        // console.log('触发地图资源加载完成事件');
        const amapLayersDom =
          containerWrapperRef.current!.getElementsByClassName('amap-layers')[0]
        const apmapMaskDom = amapLayersDom.getElementsByClassName(
          'carorg-amap-zh-mask'
        )[0]
        if (!apmapMaskDom) {
          const zhDiv = document.createElement('div')
          zhDiv.classList.add('carorg-amap-zh-mask')
          amapLayersDom.prepend(zhDiv)
        }
      })
    })
  }, [])

  return (
    <div className="large-screen-container-govern" ref={largeScreenContainer}>
      <ViewLoading show={viewLoading} />
      <div
        className="container-wrapper"
        style={{ width: `${UIWIDTH}px`, height: `${UIHEIGHT}px` }}
        ref={containerWrapperRef}
      >
        <div className="govern-map-container" id="governMapContainer"></div>
        <WrapperHeader
          prevTitle="数智治理"
          nextTitle="安全数据"
          selectedAssociationItem={selectedAssociationItem}
          onAssociationClick={handleAssociationClick}
          gotoNext={() => {
            setTimeout(() => {
              navigator('/bgBaseData')
            }, 500)
            onSlideToLeft()
          }}
          gotoPrev={() => {
            setTimeout(() => {
              navigator('/bigScreenWarn')
            }, 500)
            onSlideToRight()
          }}
          weatherPlugin={weatherPlugin}
          name="治理成效"
          isFullscreen={isFullscreen}
          onToggleFullScreen={toggleFullscreen}
        />
        <div className="govern-body">
          <div className="body-left">
            <Left
              ref={LeftCompRef}
              selectedAssociationItem={selectedAssociationItem}
            />
          </div>
          <div className="body-center">
            <Center
              ref={CenterCompRef}
              selectedAssociationItem={selectedAssociationItem}
            />
          </div>
          <div className="body-right">
            <Right
              ref={RightCompRef}
              selectedAssociationItem={selectedAssociationItem}
            />
          </div>
        </div>
      </div>
    </div>
  )
}

export default BigScreenGovern
